package com.youbang.base.interceptor;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.youbang.base.annotations.NotCheckSession;

public class UrlInterceptor implements HandlerInterceptor {

	// 在调用方法之前执行拦截
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 将handler强转为HandlerMethod
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		// 从方法处理器中获取出要调用的方法
		Method method = handlerMethod.getMethod();
		// 获取出方法上的注解
		NotCheckSession notCheckSession = method.getAnnotation(NotCheckSession.class);
		// 如果注解为null, 说明不需要拦截, 直接放过
		if(notCheckSession != null) {
			return true;
		}
		else{
			HttpSession session = request.getSession();
			Object obj = session.getAttribute("session");
			
			if(obj == null) {
				response.setContentType("text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");

				// 如果session中不存在登录者实体，则弹出框提示重新登录
				PrintWriter out = response.getWriter();
				String loginPage = request.getContextPath() + "/";//系统默认跳转登陆

				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\">");
				builder.append("alert('请登录系统后再进行操作');");
				builder.append("window.top.location.href='");
				builder.append(loginPage);
				builder.append("';");
				builder.append("</script>");
				out.print(builder.toString());
				
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//System.out.println("postHandler");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//System.out.println("afterCompletion");
	}
}
